const cloud = require("wx-server-sdk");
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
});

const db = cloud.database();
// 获取openid
const getOpenId = async () => {
  // 获取基础信息
  const wxContext = cloud.getWXContext();
  return {
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  };
};

// 获取小程序二维码
const getMiniProgramCode = async () => {
  // 获取小程序二维码的buffer
  const resp = await cloud.openapi.wxacode.get({
    path: "pages/index/index",
  });
  const { buffer } = resp;
  // 将图片上传云存储空间
  const upload = await cloud.uploadFile({
    cloudPath: "code.png",
    fileContent: buffer,
  });
  return upload.fileID;
};

// 创建集合
const createCollection = async () => {
  try {
    // 创建集合
    await db.createCollection("sales");
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "上海",
        sales: 11,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华东",
        city: "南京",
        sales: 11,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "广州",
        sales: 22,
      },
    });
    await db.collection("sales").add({
      // data 字段表示需新增的 JSON 数据
      data: {
        region: "华南",
        city: "深圳",
        sales: 22,
      },
    });
    return {
      success: true,
    };
  } catch (e) {
    // 这里catch到的是该collection已经存在，从业务逻辑上来说是运行成功的，所以catch返回success给前端，避免工具在前端抛出异常
    return {
      success: true,
      data: "create collection success",
    };
  }
};

// 查询数据
const selectRecord = async () => {
  // 返回数据库查询结果
  return await db.collection("sales").get();
};

// 更新数据
const updateRecord = async (event) => {
  try {
    // 遍历修改数据库信息
    for (let i = 0; i < event.data.length; i++) {
      await db
        .collection("sales")
        .where({
          _id: event.data[i]._id,
        })
        .update({
          data: {
            sales: event.data[i].sales,
          },
        });
    }
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 新增数据
const insertRecord = async (event) => {
  try {
    const insertRecord = event.data;
    // 插入数据
    await db.collection("sales").add({
      data: {
        region: insertRecord.region,
        city: insertRecord.city,
        sales: Number(insertRecord.sales),
      },
    });
    return {
      success: true,
      data: event.data,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

// 删除数据
const deleteRecord = async (event) => {
  try {
    await db
      .collection("sales")
      .where({
        _id: event.data._id,
      })
      .remove();
    return {
      success: true,
    };
  } catch (e) {
    return {
      success: false,
      errMsg: e,
    };
  }
};

<<<<<<< HEAD
// 用户登录
const login = async (event) => {
  try {
    const { username, password } = event;
    
    if (!username || !password) {
      return {
        success: false,
        message: '账号和密码不能为空'
      };
    }

    // 获取openid
    const wxContext = cloud.getWXContext();

    // 查询用户 - 使用 user1 集合
    let userResult;
    try {
      userResult = await db.collection('user1')
        .where({
          username: username
        })
        .get();
    } catch (e) {
      console.error('查询用户失败:', e);
      return {
        success: false,
        message: '数据库查询失败，请检查数据库集合 user1 是否存在'
      };
    }

    if (userResult.data.length === 0) {
      return {
        success: false,
        message: '账号不存在'
      };
    }

    const user = userResult.data[0];

    // 简单的密码验证（实际项目中应该使用加密）
    if (user.password !== password) {
      return {
        success: false,
        message: '密码错误'
      };
    }

    // 更新用户登录信息
    try {
      await db.collection('user1').doc(user._id).update({
        data: {
          lastLoginTime: new Date(),
          openid: wxContext.OPENID
        }
      });
    } catch (updateError) {
      // 更新失败不影响登录
      console.warn('更新登录时间失败:', updateError);
    }

    // 返回用户信息（不包含密码）
    const userInfo = {
      _id: user._id,
      username: user.username,
      email: user.email || '',
      avatar: user.avatar || '',
      nickname: user.nickname || user.username,
      openid: wxContext.OPENID
    };

    return {
      success: true,
      data: userInfo
    };
  } catch (e) {
    console.error('登录错误:', e);
    return {
      success: false,
      message: '登录失败，请稍后重试',
      errMsg: e.toString()
    };
  }
};

// 用户注册
const register = async (event) => {
  try {
    const { username, password, nickname, email } = event;
    
    // 验证必填字段
    if (!username || !password) {
      return {
        success: false,
        message: '账号和密码不能为空'
      };
    }

    // 验证账号长度
    if (username.length < 3 || username.length > 20) {
      return {
        success: false,
        message: '账号长度应为3-20个字符'
      };
    }

    // 验证密码长度
    if (password.length < 6 || password.length > 20) {
      return {
        success: false,
        message: '密码长度应为6-20个字符'
      };
    }

    // 获取openid
    const wxContext = cloud.getWXContext();

    // 检查账号是否已存在
    let checkResult;
    try {
      checkResult = await db.collection('user1')
        .where({
          username: username
        })
        .get();
    } catch (e) {
      console.error('查询用户失败:', e);
      return {
        success: false,
        message: '数据库查询失败，请检查数据库集合 user1 是否存在'
      };
    }

    if (checkResult.data.length > 0) {
      return {
        success: false,
        message: '该账号已存在，请使用其他账号'
      };
    }

    // 创建新用户
    const newUser = {
      username: username,
      password: password,
      nickname: nickname || username,
      email: email || '',
      avatar: '',
      createTime: new Date(),
      lastLoginTime: new Date(),
      openid: wxContext.OPENID
    };

    let addResult;
    try {
      addResult = await db.collection('user1').add({
        data: newUser
      });
    } catch (e) {
      console.error('创建用户失败:', e);
      return {
        success: false,
        message: '注册失败，请稍后重试',
        errMsg: e.toString()
      };
    }

    // 返回用户信息（不包含密码）
    const userInfo = {
      _id: addResult._id,
      username: newUser.username,
      email: newUser.email,
      avatar: newUser.avatar,
      nickname: newUser.nickname,
      openid: wxContext.OPENID
    };

    return {
      success: true,
      message: '注册成功',
      data: userInfo
    };
  } catch (e) {
    console.error('注册错误:', e);
    return {
      success: false,
      message: '注册失败，请稍后重试',
      errMsg: e.toString()
    };
  }
};

=======
>>>>>>> 6f797a20ba07878009f51ca3cf3c354cee81e558
// const getOpenId = require('./getOpenId/index');
// const getMiniProgramCode = require('./getMiniProgramCode/index');
// const createCollection = require('./createCollection/index');
// const selectRecord = require('./selectRecord/index');
// const updateRecord = require('./updateRecord/index');
// const sumRecord = require('./sumRecord/index');
// const fetchGoodsList = require('./fetchGoodsList/index');
// const genMpQrcode = require('./genMpQrcode/index');
// 云函数入口函数
exports.main = async (event, context) => {
  switch (event.type) {
    case "getOpenId":
      return await getOpenId();
    case "getMiniProgramCode":
      return await getMiniProgramCode();
    case "createCollection":
      return await createCollection();
    case "selectRecord":
      return await selectRecord();
    case "updateRecord":
      return await updateRecord(event);
    case "insertRecord":
      return await insertRecord(event);
    case "deleteRecord":
      return await deleteRecord(event);
<<<<<<< HEAD
    case "login":
      return await login(event);
    case "register":
      return await register(event);
    default:
      return {
        success: false,
        message: '未知的操作类型'
      };
=======
>>>>>>> 6f797a20ba07878009f51ca3cf3c354cee81e558
  }
};
